<?php
namespace Cmf\Controllers;

use Phalcon\Mvc\Controller;
use Cmf\Models\Menu;
use Cmf\Models\Tree;
use Cmf\Library\Category\Category;

/**
 * Admin模块总控制器
 */
class BaseController extends Controller
{
	public function beforeExecuteRoute()
	{
		$identity = $this->session->get('auth_identity');
		$actionName = $this->dispatcher->getActionName();
		$controllerName = $this->dispatcher->getControllerName();
		$this->session->set('resource',['action' => $actionName,'controller' => $controllerName]);

		if(!is_array($identity)) {
			$this->response->redirect('session/login');
			$this->session->destroy();
			return false;
		}

		if(!$this->acl->isAllowed($identity['role_title'],$controllerName,$actionName)) {
			$this->flash->warning('没有权限访问');
			$this->response->redirect('index/index');
			$this->session->destroy();
			return false;
		}
	}

	public function initialize()
	{
		$cate = new Category();
		$menu = menu::find();
		$tree = tree::listToTree($menu->toArray());

		$cid = 0;
		$url = $this->dispatcher->getControllerName().'/'.$this->dispatcher->getActionName();
		foreach($menu->toArray() as $key => $value) {
			if($url == $value['url']) {
				$cid = $value['id'];
			}
		}
		$nav = $cate::getParents($menu->toArray(),$cid);

		$this->view->nav = $nav;
		$this->view->tree = $tree;
		$this->view->user = $this->session->get('auth_identity');
	}
}
